import Vue from 'vue'
import Vuex from 'vuex';
import axios from 'axios'
import {dateFormat} from '../util/index'
import marked from 'marked'

Vue.use(Vuex);

const store = new Vuex.Store({

    state: {
        count: 1,
        getList: [],
        getTags: [],
        getHot: []
    },

    actions: {

        // 获取文章列表
        getCaptcha({commit}) {
            axios.get('/api/captcha').then((res)=>{
                let {data} = res;
                if(data.code == 200) {       
                    commit('getCaptcha', data.docs);
                    commit('getTsList', data.tags);
                }
            })
        },

        // 获取热门文章
        getHotArticle({commit}) {
            axios.get('/api/hot').then(res=>{
                let {data} = res;
                if(data.code == 200) {
                    commit('getHotArticle', data.docs);
                }
            });
        }


    },

    mutations: {

        getCaptcha(state, value){
            state.getList = value;
        },

        getTsList(state, value){
            state.getTags = value;
        },

        getHotArticle(state, value){
            state.getHot = value;
        }

    },

    getters: {
        getGetCaptcha: state =>{
            return state.getList.map(item=>{
                item.content = marked(item.content);
                let year = new Date(Number(item.date)).getFullYear();
                let month = new Date(Number(item.date)).getMonth() + 1;
                let day = new Date(Number(item.date)).getDate();
                if(month < 10) month = '0' + month;
                item.date = dateFormat(year + '-' + month + '-' + day, 'yyyy.MM.dd');
                return item;
            })
        },

        getGetTsList: state => state.getTags,

        getGetHotArticle: state => {
            return state.getHot.map(item=>{
                if(item.title && item._id){
                    return item;
                }
            })
        }
    }
})

export default store;
